﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using YAGMRC.Core.Models.GetGamesAndPlayers;
using YAGMRC.Core.Models.SubmitTurn;
using YAGMRC.Core.OS;

namespace YAGMRC.Core.Commands
{
    public class SubmitTurnCommand : ICommand<SubmitTurnCommandParam>, IResult<SubmitTurnResult>
    {
        #region Constructor

        private SubmitTurnCommand()
        {
        }

        internal SubmitTurnCommand(Resolver resolver)
        {
            m_Resolver = resolver;
        }

        #endregion Constructor

        private Resolver m_Resolver;

        public void Execute(SubmitTurnCommandParam parameter)
        {
            this.Result = new SubmitTurnResult();

            if (!CanExecute())
            {
                return;
            }

            WebUpload cmd = m_Resolver.Get<WebUpload>();
            if (!cmd.CanExecute())
            {
                return;
            }

            DirectoryInfo path = m_Resolver.Get<IOSSetting>().CIVSaveGamePath;

            int gameid = parameter.GameID;
            YAGMRC.Core.Models.GetGamesAndPlayers.GetGamesAndPlayersCommandResult games = m_Resolver.Get<YAGMRC.Core.Models.GetGamesAndPlayers.GetGamesAndPlayersCommandResult>();

            Game foundGame = (from id in games.Result.Games where id.GameId == gameid select id).FirstOrDefault();
            if (null == foundGame)
            {
                return;
            }

            FileInfo file = Helper.File(foundGame.GameId, m_Resolver.Get<IOSSetting>());
            if (!file.Exists)
            {
                return;
            }

            AuthenticateCommandResult auth = m_Resolver.Get<AuthenticateCommandResult>();

            cmd.Execute(new WebUploadParam("Game/UploadSaveClient", file, File.ReadAllBytes(file.FullName), auth.AuthID, foundGame.CurrentTurn.TurnId));
            this.Result = cmd.Result.Result;

            if (parameter.DoDeleteAfterUpload)
            {
                file.Delete();
            }
        }

        public bool CanExecute()
        {
            AuthenticateCommandResult auth = m_Resolver.Get<AuthenticateCommandResult>();
            if ((null != auth) && (auth.Authenticated))
            {
                return true;
            }

            return false;
        }

        public SubmitTurnResult Result
        {
            get;
            private set;
        }
    }
}